﻿using System;
using System.Data;
using System.IO;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Text;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.VisualBasic;
using Interface.Clinical;
using Interface.Security;
using Application.Common;
using Interface.Administration;
using Application.Presentation;

/// /////////////////////////////////////////////////////////////////////
// Code Written By   : Jayant Kumar Das
// Written Date      : 15 August 2012
// Description       : ART History for Kenya Blue Card
//
/// /////////////////////////////////////////////////////////////////
public partial class ClinicalForms_frmClinical_ARTHistory : System.Web.UI.Page
{
    public int SelectedPurposeId;
    public string SelectedRegimen, SelectedLastused;

    protected void GetARTHistoryData()
    {
        DataSet theDSARTHistory = new DataSet();

        IPriorArtHivCare ARTHistoryMgr = (IPriorArtHivCare)ObjectFactory.CreateInstance("BusinessProcess.Clinical.BPriorArtHivCare, BusinessProcess.Clinical");
        theDSARTHistory = ARTHistoryMgr.GetARTHistoryData(Convert.ToInt32(Session["PatientId"]), Convert.ToInt32(Session["PatientVisitId"]), Convert.ToInt32(Session["AppLocationId"]));
        ViewState["gridSortDirection"] = "Desc";
        if (Convert.ToInt32(theDSARTHistory.Tables[0].Rows[0]["VisitId"]) > 0)
        {
            Session["PatientVisitId"] = Convert.ToInt32(theDSARTHistory.Tables[0].Rows[0]["VisitId"]);
            txtTransferInDate.Value = String.Format("{0:dd-MMM-yyyy}", theDSARTHistory.Tables[1].Rows[0]["ARTTransferInDate"]);
            dddistrict.SelectedValue = Convert.ToString(theDSARTHistory.Tables[1].Rows[0]["FromDistrict"]);
            ddfacility.SelectedValue = Convert.ToString(theDSARTHistory.Tables[1].Rows[0]["ARTTransferInFrom"]);
            txtDateARTStarted.Value = String.Format("{0:dd-MMM-yyyy}", theDSARTHistory.Tables[3].Rows[0]["ARTStartDate"]);
            txtHIVConfirmHIVPosDate.Value = String.Format("{0:dd-MMM-yyyy}", theDSARTHistory.Tables[3].Rows[0]["ConfirmHIVPosDate"]);

            if (Convert.ToInt32(theDSARTHistory.Tables[2].Rows.Count)>0)
            {
                txtWhere.Text = theDSARTHistory.Tables[2].Rows[0]["HIVCareWhere"].ToString();
            }

            if (Convert.ToInt32(theDSARTHistory.Tables[2].Rows.Count) > 0)
            {
                if (Convert.ToInt32(theDSARTHistory.Tables[2].Rows[0]["PriorART"]) == 1)
                {
                    rbtnknownYes.Checked = true;
                }
                else if (Convert.ToInt32(theDSARTHistory.Tables[2].Rows[0]["PriorART"]) == 0)
                {
                    rbtnknownNo.Checked = true;
                }
            }
            ddlWHOStage.Text = theDSARTHistory.Tables[4].Rows[0]["WHOStage"].ToString();
            txtAreaAllergy.Value = theDSARTHistory.Tables[5].Rows[0]["DrugAllergies"].ToString();
            txtEnrolledinHIVCare.Value = String.Format("{0:dd-MMM-yyyy}", theDSARTHistory.Tables[6].Rows[0]["RegistrationDate"]);
            GrdPriorART.Columns.Clear();
            BindGrid();
            GrdPriorART.DataSource = theDSARTHistory.Tables[7];
            GrdPriorART.DataBind();
            ViewState["GridData"] = theDSARTHistory.Tables[7];
        }
        else { txtEnrolledinHIVCare.Value = String.Format("{0:dd-MMM-yyyy}", theDSARTHistory.Tables[1].Rows[0]["RegistrationDate"]); }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        (Master.FindControl("lblRoot") as Label).Text = "Clinical Forms >>";
        (Master.FindControl("lblheader") as Label).Text = "ART History";
        (Master.FindControl("lblMark") as Label).Visible = false;
        (Master.FindControl("lblformname") as Label).Text = "ART History";
        if (!IsPostBack)
        {
            Authenticate();
            FillDropDown();
            Init_ARTHistory();
            GetARTHistoryData();
        }
        else
        {
            if ((DataTable)Application["AddRegimen"] != null)
            {
                DataTable theDT = (DataTable)Application["AddRegimen"];
                ViewState["SelectedData"] = theDT;
                string theStr = FillRegimen(theDT);
                txtRegimen.Text = theStr;
                Application.Remove("AddRegimen");
            }
        }
    }
    private string FillRegimen(DataTable theDT)
    {
        string theRegimen = "";
        DataView theDV = new DataView();
        if (theDT.Rows.Count != 0)
        {
            for (int i = 0; i < theDT.Rows.Count; i++)
            {
                DataTable theFilDT = (DataTable)ViewState["MasterARVData"];
                if (theFilDT.Rows.Count > 0)
                {
                    theDV = new DataView(theFilDT);
                    theDV.RowFilter = "DrugId = " + theDT.Rows[i]["DrugId"]; 
                    if (theDV.Count > 0)
                    {
                        for (int j = 0; j < theDV.Count; j++)
                        {
                            if (theRegimen == "")
                            {
                                theRegimen = theDV[j]["Abbr"].ToString();
                            }
                            else
                            {
                                theRegimen = theRegimen + "/" + theDV[j]["Abbr"].ToString();
                            }
                        }
                    }
                }
                theRegimen = theRegimen.Trim();

            }
        }
        return theRegimen;
    }
    protected void FillDropDown()
    {
        BindFunctions theBndMgr = new BindFunctions();
        DataSet theDS = new DataSet();
        theDS.ReadXml(MapPath("..\\XMLFiles\\ALLMasters.con"));
        IQCareUtils theUtils = new IQCareUtils();

        if (theDS.Tables["Mst_District"] != null)
        {
            DataView theDV = new DataView(theDS.Tables["Mst_District"]);
            theDV.RowFilter = "DeleteFlag=0";
            if (theDV.Table != null)
            {
                DataTable theDT = (DataTable)theUtils.CreateTableFromDataView(theDV);
                theBndMgr.BindCombo(dddistrict, theDT, "Name", "ID");
            }
        }
        if (theDS.Tables["Mst_Facility"] != null)
        {
            DataView theDV = new DataView(theDS.Tables["Mst_Facility"]);
            theDV.RowFilter = "DeleteFlag=0";
            if (theDV.Table != null)
            {
                DataTable theDT = (DataTable)theUtils.CreateTableFromDataView(theDV);
                theBndMgr.BindCombo(ddfacility, theDT, "FacilityName", "FacilityID");
            }
        }
        if (theDS.Tables["Mst_Decode"] != null)
        {
            DataView theDV = new DataView(theDS.Tables["Mst_Decode"]);
            theDV.RowFilter = "DeleteFlag=0 and CodeId=33";
            if (theDV.Table != null)
            {
                DataTable theDT = (DataTable)theUtils.CreateTableFromDataView(theDV);
                theBndMgr.BindCombo(ddlpurpose, theDT, "Name", "ID");
            }
        }

        if (theDS.Tables["Mst_Decode"] != null)
        {
            DataView theDV = new DataView(theDS.Tables["Mst_Decode"]);
            theDV.RowFilter = "(DeleteFlag = 0 or DeleteFlag IS NULL) and SystemId in(0,1) and CodeId=22";
            theDV.Sort = "SRNo";
            if (theDV.Table != null)
            {
                DataTable theDT = (DataTable)theUtils.CreateTableFromDataView(theDV);
                theBndMgr.BindCombo(ddlWHOStage, theDT, "Name", "ID");
            }
        }
    }
    protected void Init_ARTHistory()
    {
        
        IPatientARTCare ARTHistoryMgr = (IPatientARTCare)ObjectFactory.CreateInstance("BusinessProcess.Clinical.BPatientARTCare, BusinessProcess.Clinical");
        DataSet theDS = ARTHistoryMgr.GetPatientARTCare(Convert.ToInt32(Session["PatientId"]), Convert.ToInt32(Session["AppLocationId"]));
        ViewState["MasterARVData"] = theDS.Tables[1];

    }
    private void BindGrid()
    {
        BoundField theCol0 = new BoundField();
        theCol0.HeaderText = "VisitId";
        theCol0.DataField = "VisitId";
        theCol0.ItemStyle.CssClass = "textstyle";
        GrdPriorART.Columns.Add(theCol0);

        BoundField theCol1 = new BoundField();
        theCol1.HeaderText = "Patientid";
        theCol1.DataField = "ptn_pk";
        theCol1.ItemStyle.CssClass = "textstyle";
        GrdPriorART.Columns.Add(theCol1);
        
        BoundField theCol6 = new BoundField();
        theCol6.HeaderText = "PurposeId";
        theCol6.DataField = "PurposeId";
        GrdPriorART.Columns.Add(theCol6);

        BoundField theCol2 = new BoundField();
        theCol2.HeaderText = "Purpose";
        theCol2.DataField = "Purpose";
        theCol2.SortExpression = "Purpose";
        theCol2.ReadOnly = true;
        GrdPriorART.Columns.Add(theCol2);

        BoundField theCol3 = new BoundField();
        theCol3.HeaderText = "Regimen";
        theCol3.DataField = "Regimen";
        theCol3.SortExpression = "Regimen";
        theCol3.ReadOnly = true;
        GrdPriorART.Columns.Add(theCol3);

        BoundField theCol4 = new BoundField();
        theCol4.HeaderText = "Regimen Last Used";
        theCol4.DataField = "RegLastUsed";
        theCol4.DataFormatString = "{0:dd-MMM-yyyy}";
        theCol4.SortExpression = "RegLastUsed";
        theCol4.ReadOnly = true;
        GrdPriorART.Columns.Add(theCol4);

        CommandField theCol5 = new CommandField();
        theCol5.ButtonType = ButtonType.Link;
        theCol5.DeleteText = "<img src='../Images/del.gif' alt='Delete this' border='0' />";
        theCol5.ShowDeleteButton = true;
        GrdPriorART.Columns.Add(theCol5);

        GrdPriorART.Columns[0].Visible = false;
        GrdPriorART.Columns[1].Visible = false;
        GrdPriorART.Columns[2].Visible = false;
    }
    private void Refresh()
    {
        ddlpurpose.SelectedIndex = -1;
        txtRegimen.Text = "";
        txtLastUsed.Text = "";

    }
    protected void btnAddPriorART_Click(object sender, EventArgs e)
    {
        if (ValidateLastUsed() == false)
        {
            return;
        }
        int VisitId=Convert.ToInt32(Session["PatientVisitId"]) > 0 ? Convert.ToInt32(Session["PatientVisitId"]) : 0;
        DataTable theDT = new DataTable();
        if ((DataTable)ViewState["GridData"] == null)
        {
            theDT.Columns.Add("ptn_pk", typeof(Int32));
            theDT.Columns.Add("VisitId", typeof(Int32));
            theDT.Columns.Add("PurposeId", typeof(Int32));
            theDT.Columns.Add("Purpose", typeof(string));
            theDT.Columns.Add("Regimen", typeof(string));
            theDT.Columns.Add("RegLastUsed", typeof(string));
            DataRow theDR = theDT.NewRow();
            theDR["ptn_pk"] = Session["PatientId"];
            theDR["VisitId"] = VisitId;
            theDR["Purpose"] = ddlpurpose.SelectedItem.Text;
            theDR["Regimen"] = txtRegimen.Text;
            if (!string.IsNullOrEmpty(txtLastUsed.Text))
                theDR["RegLastUsed"] = txtLastUsed.Text;

            theDR["PurposeId"] = ddlpurpose.SelectedValue;
            theDT.Rows.Add(theDR);
            GrdPriorART.Columns.Clear();
            BindGrid();
            Refresh();
            GrdPriorART.DataSource = theDT;
            GrdPriorART.DataBind();
            ViewState["GridData"] = theDT;
        }
        else
        {

            theDT = (DataTable)ViewState["GridData"];
            if (Convert.ToInt32(ViewState["UpdateFlag"]) == 1)
            {
                DataRow[] rows = theDT.Select("PurposeId=" + ViewState["SelectedPurposeId"] + " and Regimen='" + ViewState["SelectedRegimen"] + "' and RegLastUsed='" + ViewState["SelectedLastused"] + "'"); 
                for(int i = 0; i < rows.Length; i ++) 
                {
                    rows[i]["ptn_pk"] = Session["PatientId"];
                    rows[i]["VisitId"] = VisitId;
                    rows[i]["PurposeId"] = ddlpurpose.SelectedValue;
                    rows[i]["Purpose"] = ddlpurpose.SelectedItem.Text;
                    rows[i]["Regimen"] = txtRegimen.Text;
                    if (!string.IsNullOrEmpty(txtLastUsed.Text))
                        rows[i]["RegLastUsed"] = txtLastUsed.Text;
                    theDT.AcceptChanges();} 
                GrdPriorART.Columns.Clear();
                BindGrid();
                Refresh();
                GrdPriorART.DataSource = theDT;
                GrdPriorART.DataBind();
                ViewState["GridData"] = theDT;
                ViewState["UpdateFlag"] ="0";
            }
            else
            {
                DataRow theDR = theDT.NewRow();
                theDR["ptn_pk"] = Session["PatientId"];
                theDR["VisitId"] = VisitId;
                theDR["Purpose"] = ddlpurpose.SelectedItem.Text;
                theDR["Regimen"] = txtRegimen.Text;
                if (!string.IsNullOrEmpty(txtLastUsed.Text))
                    theDR["RegLastUsed"] = txtLastUsed.Text;
                theDR["PurposeId"] = ddlpurpose.SelectedValue;
                theDT.Rows.Add(theDR);
                GrdPriorART.Columns.Clear();
                BindGrid();
                Refresh();
                GrdPriorART.DataSource = theDT;
                GrdPriorART.DataBind();
                ViewState["GridData"] = theDT;
            }
        }
       
    }
    protected void btnRegimen_Click(object sender, EventArgs e)
    {
        string theScript;
        Application.Add("MasterData", ViewState["MasterARVData"]);
        Application.Add("SelectedDrug", (DataTable)ViewState["SelectedData"]);
        theScript = "<script language='javascript' id='DrgPopup'>\n";
        theScript += "window.open('../Pharmacy/frmDrugSelector.aspx?DrugType=37&btnreg=" + btnRegimen.ID + "' ,'DrugSelection','toolbars=no,location=no,directories=no,dependent=yes,top=10,left=30,maximize=no,resize=no,width=700,height=350,scrollbars=yes');\n";
        theScript += "</script>\n";
        Page.RegisterStartupScript("DrgPopup", theScript);
    }
    protected void GrdPriorART_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            for (int i = 0; i < e.Row.Cells.Count; i++)
            {
                if (e.Row.Cells[0].Text.ToString() != "0")
                {
                    if (i != 6)
                    {
                        e.Row.Cells[i].Attributes.Add("onmouseover", "this.style.cursor='pointer';this.style.BackColor='#666699';");
                        e.Row.Cells[i].Attributes.Add("onmouseout", "this.style.backgroundColor='';");
                        e.Row.Cells[i].Attributes.Add("onclick", Page.ClientScript.GetPostBackEventReference(GrdPriorART, "Select$" + e.Row.RowIndex.ToString()));
                    }
                }
                if (e.Row.Cells[5].Text.ToString() == "01-Jan-1900")
                {
                    e.Row.Cells[5].Text = "";
                }

            }
        }
    }
    protected void GrdPriorART_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        int thePage = GrdPriorART.PageIndex;
        int thePageSize = GrdPriorART.PageSize;
        GridViewRow theRow = GrdPriorART.Rows[e.NewSelectedIndex];
        int theIndex = thePageSize * thePage + theRow.RowIndex;
        System.Data.DataTable theDT = new System.Data.DataTable();
        theDT = ((DataTable)ViewState["GridData"]);
        int r = theIndex;
        if (theDT.Rows.Count > 0)
        {
            ViewState["UpdateFlag"] = 1;
            ddlpurpose.SelectedValue= theDT.Rows[r]["PurposeId"].ToString();
            ViewState["SelectedPurposeId"] = Convert.ToInt32(theDT.Rows[r]["PurposeId"]);
            txtRegimen.Text = theDT.Rows[r]["Regimen"].ToString();
            ViewState["SelectedRegimen"] = theDT.Rows[r]["Regimen"].ToString();
            if (!string.IsNullOrEmpty(theDT.Rows[r]["RegLastUsed"].ToString()))
            {
                string strdateformat = String.Format("{0:dd-MMM-yyyy}", theDT.Rows[r]["RegLastUsed"]);
                if (strdateformat.Trim() != "01-Jan-1900")
                {
                    txtLastUsed.Text = strdateformat;
                }
            }
            ViewState["SelectedLastused"] = theDT.Rows[r]["RegLastUsed"].ToString();
        }
    }
    protected Hashtable HT(int qltyFlag)
    {
        
        Hashtable theHT = new Hashtable();
        try
        {
            theHT.Add("PatientId", Session["PatientId"]);
            theHT.Add("VisitId", Session["PatientVisitId"]);
            theHT.Add("LocationId", Session["AppLocationId"]);
            theHT.Add("TransferInDate", txtTransferInDate.Value);
            theHT.Add("dddistrict", dddistrict.SelectedValue);
            theHT.Add("ddfacility", ddfacility.SelectedValue);
            theHT.Add("DateARTStarted", txtDateARTStarted.Value);
            int priorART = rbtnknownYes.Checked ? 1 : rbtnknownNo.Checked ? 0 : 9;
            theHT.Add("priorART", priorART);
            theHT.Add("ConfirmHIVPosDate", txtHIVConfirmHIVPosDate.Value);
            theHT.Add("Where", txtWhere.Text);
            theHT.Add("EnrolledinHIVCare", txtEnrolledinHIVCare.Value);
            theHT.Add("WHOStage", ddlWHOStage.SelectedValue);
            theHT.Add("AreaAllergy", txtAreaAllergy.Value);
            theHT.Add("UserID", Session["AppUserId"].ToString());
            if (qltyFlag == 1)
            {
                theHT.Add("qltyFlag", "1");
            }
            else
            {
                theHT.Add("qltyFlag", "0");
            } 
        }
        catch (Exception err)
        {
            MsgBuilder theMsg = new MsgBuilder();
            theMsg.DataElements["MessageText"] = err.Message.ToString();
            IQCareMsgBox.Show("#C1", theMsg, this);
        }
        return theHT;

    }
    private void SaveCancel()
    {

        string script = "<script language = 'javascript' defer ='defer' id = 'confirm'>\n";
        script += "var ans;\n";

        script += "ans=window.confirm('ART History Form saved successfully. Do you want to close?');\n";
        script += "if (ans==true)\n";
        script += "{\n";
        if (ViewState["Redirect"] == "0")
        {
            script += "window.location.href='frmPatient_Home.aspx';\n";
        }
        else
        {
            script += "window.location.href='frmPatient_History.aspx?sts=" + 0 + "';\n";
        }
        script += "}\n";
        script += "else \n";
        script += "{\n";
        script += "window.location.href='frmClinical_ARTHistory.aspx';\n";
        script += "}\n";
        script += "</script>\n";
        RegisterStartupScript("confirm", script);
    }
    private void Authenticate()
    {
        AuthenticationManager Authentication = new AuthenticationManager();
        /***************** Check For User Rights ****************/
        if (Authentication.HasFunctionRight(ApplicationAccess.ARTHistory, FunctionAccess.Print, (DataTable)Session["UserRight"]) == false)
        {
            btnPrint.Enabled = false;
        }
        if (Convert.ToInt32(Session["PatientVisitId"]) == 0)
        {
            if (Authentication.HasFunctionRight(ApplicationAccess.ARTHistory, FunctionAccess.Add, (DataTable)Session["UserRight"]) == false)
            {
                btnsave.Enabled = false;
                btncomplete.Enabled = false;
            }
        }

        else
        {
            if (Authentication.HasFunctionRight(ApplicationAccess.ARTHistory, FunctionAccess.View, (DataTable)Session["UserRight"]) == false)
            {
                string theUrl = "";
                theUrl = string.Format("{0}?sts={1}", "frmPatient_History.aspx", Session["HIVPatientStatus"].ToString());
                Response.Redirect(theUrl);
            }
            else if (Authentication.HasFunctionRight(ApplicationAccess.ARTHistory, FunctionAccess.Update, (DataTable)Session["UserRight"]) == false)
            {
                btnsave.Enabled = false;
                btncomplete.Enabled = false;
            }
            if (Convert.ToString(Session["HIVPatientStatus"]) == "1")
            {
                btnsave.Enabled = false;
                btncomplete.Enabled = false;
            }
            //Privilages for Care End
            if (Convert.ToString(Session["CareEndFlag"]) == "1")
            {
                btnsave.Enabled = true;
                btncomplete.Enabled = true;
            }
        }
    }
    private Boolean ValidateLastUsed()
    {
        IQCareUtils theUtil = new IQCareUtils();
        if (Convert.ToDateTime(Application["AppCurrentDate"]) < Convert.ToDateTime(theUtil.MakeDate(txtLastUsed.Text)))
        {
            IQCareMsgBox.Show("CmpLastUsed", this);
            txtLastUsed.Focus();
            return false;
        }
        else if (ddlpurpose.SelectedValue == "0")
        {
            IQCareMsgBox.Show("ChkPurpose", this);
            txtLastUsed.Focus();
            return false;
        }
        return true;
    }
    private Boolean fieldValidation()
    {
        IQCareUtils theUtil = new IQCareUtils();

        int priorART = rbtnknownYes.Checked == true ? 1 : rbtnknownNo.Checked == true ? 0 : 9;
        if (priorART == 9)
        {
            IQCareMsgBox.Show("ChkPriorART", this);
            return false;
        }

        else if (Convert.ToDateTime(Application["AppCurrentDate"]) < Convert.ToDateTime(theUtil.MakeDate(txtTransferInDate.Value)))
        {
            IQCareMsgBox.Show("CmpTransfInDate", this);
            txtTransferInDate.Focus();
            return false;
        }

        else if (Convert.ToDateTime(Application["AppCurrentDate"]) < Convert.ToDateTime(theUtil.MakeDate(txtDateARTStarted.Value)))
        {
            IQCareMsgBox.Show("CmpStartART", this);
            txtDateARTStarted.Focus();
            return false;
        }

        else if (Convert.ToDateTime(Application["AppCurrentDate"]) < Convert.ToDateTime(theUtil.MakeDate(txtHIVConfirmHIVPosDate.Value)))
        {
            IQCareMsgBox.Show("CmpConHIVPositive", this);
            txtHIVConfirmHIVPosDate.Focus();
            return false;
        }
        else if (priorART == 1)
        {
            if (GrdPriorART.Rows.Count == 0)
            {
                IQCareMsgBox.Show("ChkGrid", this);
                txtHIVConfirmHIVPosDate.Focus();
                return false;
            }
        }
        return true;
    }
    protected void btnsave_Click(object sender, EventArgs e)
    {

        if (fieldValidation() == false)
        {
            return;
        }
        Hashtable theHT = HT(0);
        DataTable theDT = new DataTable();
        if ((DataTable)ViewState["GridData"] == null)
        {
            theDT.Columns.Add("ptn_pk", typeof(Int32));
            theDT.Columns.Add("VisitId", typeof(Int32));
            theDT.Columns.Add("PurposeId", typeof(Int32));
            theDT.Columns.Add("Purpose", typeof(string));
            theDT.Columns.Add("Regimen", typeof(string));
            theDT.Columns.Add("RegLastUsed", typeof(string));
        }
        else { theDT = (DataTable)ViewState["GridData"]; }
        IPriorArtHivCare ARTHistoryMgr = (IPriorArtHivCare)ObjectFactory.CreateInstance("BusinessProcess.Clinical.BPriorArtHivCare, BusinessProcess.Clinical");
        DataTable DT = ARTHistoryMgr.Save_Update_ARVHistory(theHT, theDT);
        Session["Redirect"] ="0";
        if (Convert.ToInt32(DT.Rows[0]["VisitId"]) > 0)
        {
            SaveCancel();
        }

    }
    protected void btncomplete_Click(object sender, EventArgs e)
    {
        Hashtable theHT = HT(1);
        DataTable theDT = new DataTable();
        if ((DataTable)ViewState["GridData"] == null)
        {
            theDT.Columns.Add("ptn_pk", typeof(Int32));
            theDT.Columns.Add("VisitId", typeof(Int32));
            theDT.Columns.Add("PurposeId", typeof(Int32));
            theDT.Columns.Add("Purpose", typeof(string));
            theDT.Columns.Add("Regimen", typeof(string));
            theDT.Columns.Add("RegLastUsed", typeof(string));
        }
        else { theDT = (DataTable)ViewState["GridData"]; }
        IPriorArtHivCare ARTHistoryMgr = (IPriorArtHivCare)ObjectFactory.CreateInstance("BusinessProcess.Clinical.BPriorArtHivCare, BusinessProcess.Clinical");
        DataTable DT = ARTHistoryMgr.Save_Update_ARVHistory(theHT, theDT);
        Session["Redirect"] = "0";
        if (Convert.ToInt32(DT.Rows[0]["VisitId"]) > 0)
        {
            SaveCancel();
        }
    }
    protected void btnback_Click(object sender, EventArgs e)
    {
        string theUrl = "";
        if (Convert.ToInt32(Session["PatientVisitId"]) == 0)
        {
            theUrl = string.Format("{0}?PatientId={1}", "frmPatient_Home.aspx", Session["PatientId"].ToString());
        }
        else if (Convert.ToInt32(Session["PatientVisitId"]) > 0)
        {
            theUrl = string.Format("{0}", "frmPatient_History.aspx");

        }

        Response.Redirect(theUrl);
    }
    protected void btnPrint_Click(object sender, EventArgs e)
    {
        
    }
    protected void GrdPriorART_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        System.Data.DataTable theDT = new System.Data.DataTable();
        theDT = ((DataTable)ViewState["GridData"]);
        int r = Convert.ToInt32(e.RowIndex.ToString());

        int Id = -1;
        try
        {
            if (theDT.Rows.Count > 0)
            {

                if (theDT.Rows[r].HasErrors == false)
                {
                    if ((theDT.Rows[r]["PurposeId"] != null) && (theDT.Rows[r]["PurposeId"] != DBNull.Value))
                    {
                        if (theDT.Rows[r]["PurposeId"].ToString() != "")
                        {
                            Id = Convert.ToInt32(theDT.Rows[r]["PurposeId"]);
                            theDT.Rows[r].Delete();
                            theDT.AcceptChanges();
                            ViewState["GridData"] = theDT;
                            GrdPriorART.Columns.Clear();
                            BindGrid();
                            Refresh();
                            GrdPriorART.DataSource = (DataTable)ViewState["GridData"];
                            GrdPriorART.DataBind();
                            IQCareMsgBox.Show("DeleteSuccess", this);
                        }
                    }
                }



                if (((DataTable)ViewState["GridData"]).Rows.Count == 0)
                    btnAddPriorART.Enabled = false;
                else
                    btnAddPriorART.Enabled = true;
            }
            else
            {
                GrdPriorART.Visible = false;
                //IQCareMsgBox.Show("DeleteSuccess", this);
                Refresh();
            }
        }
        catch (Exception ex)
        {
            string str = ex.Message;
        }
    }
    protected void GrdPriorART_Sorting(object sender, GridViewSortEventArgs e)
    {
        //Init_Form(); 
        GridView theGD = (GridView)sender;
        IQCareUtils SortManager = new IQCareUtils();
        DataView theDV;
        if (ViewState["gridSortDirection"].ToString() == "Asc")
        {
            theDV = SortManager.GridSort((DataTable)this.ViewState["GridData"], e.SortExpression.ToString(), ViewState["gridSortDirection"].ToString());
            ViewState["gridSortDirection"] = "Desc";
        }
        else
        {
            theDV = SortManager.GridSort((DataTable)this.ViewState["GridData"], e.SortExpression.ToString(), ViewState["gridSortDirection"].ToString());
            ViewState["gridSortDirection"] = "Asc";
        }

        Refresh();
        GrdPriorART.DataSource = theDV;
        GrdPriorART.DataBind();
        //ViewState["GridData"] = theDV;
    }
}